#include <opencv2/opencv.hpp>
#include <iostream>

using namespace std;
using namespace cv;

int main(int argc, char* argv[])
{
    Mat in_frame, out_frame;
    const char win1[] = "Grabbing ...", win2[] = "Recording ...";
    double fps = 30;  // Frames per second
    char file_out[] = "recorded.avi";

    VideoCapture inVid(0);  // Open default camera
    if (!inVid.isOpened()) {
        cout << "Error! Camera not ready ...\n";
        return -1;
    }

    // Gets the width and height of the input video
    int width = (int)inVid.get(CAP_PROP_FRAME_WIDTH);
    int height = (int)inVid.get(CAP_PROP_FRAME_HEIGHT);
    VideoWriter recVid(file_out, VideoWriter::fourcc('M','J','P','G'),
                       fps, Size(width, height));
    if (!recVid.isOpened()) {
        cout << "Error! Video file not opened ...\n";
        return -1;
    }

    // Create two windows for orig and final video
    namedWindow(win1);
    namedWindow(win2);
    while (true) {
        // Read frame from camera (grabbing and decoding)
        inVid >> in_frame;
        // Convert the frame to grayscale
        cvtColor(in_frame, out_frame, COLOR_BGR2GRAY);
        // Write frame to video file (encoding and saving)
        recVid << out_frame;
        imshow(win1, in_frame);
        imshow(win2, out_frame);
        if (waitKey(1000/fps) >= 0)
            break;
    }
    inVid.release();  // close camera;

    return 0;
}

